<script lang="ts" setup>
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePptx from '@vue-office/pptx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
import '@vue-office/docx/lib/index.css'
import { FileUtils } from "/@/utils/FileUtils.ts";
import * as url from "url";
import { ElMessage } from 'element-plus'; // **MODIFIED**: 引入 ElMessage

const dialogVisible = ref(false)

const props = defineProps({
  modelValue: {

  }
})

const officeType = ref(null)
const preview = () => {
  // **MODIFIED**: 检查是否有预览内容
  if (!props.modelValue) {
    ElMessage.warning('无预览文件');
    return;
  }
  dialogVisible.value = true
}
const previewFile = ref(null)
const downloadFile = () => {
  // **MODIFIED**: 检查是否有预览内容
  if (!props.modelValue) {
    ElMessage.warning('无预览文件');
    return;
  }
  axios.request({
    url: props.modelValue,
    responseType: 'blob'
  }).then((response) => {
    console.log(response);

    const blob = response.data

    // 默认文件名
    let filename = FileUtils.getFileNameFromUrl(props.modelValue)

    // 如果后端有返回 Content-Disposition
    const disposition = response.headers['content-disposition']
    if (disposition && disposition.includes('filename=')) {
      filename = decodeURIComponent(disposition.split('filename=')[1])
    }

    const file = new File([blob], filename, { type: blob.type })

    const uploadFile = {
      name: file.name,
      size: file.size,
      type: file.type,
      raw: file,         // el-upload 会把它挂 raw 属性
      uid: Date.now(),   // uid 是 el-upload 的唯一标识
      status: 'ready'
    }

    previewFile.value = uploadFile

    preview()
  })
}
watch(() => props.modelValue, () => {
  if (props.modelValue) {
    officeType.value = FileUtils.getOfficeType(props.modelValue)
  }
}, { immediate: true })
</script>

<template>
  <div>
    <el-button @click="downloadFile">预览</el-button>
  </div>
  <teleport to="body">
    <ElDialog v-model="dialogVisible" title="预览" :append-to-body="false" style="width: 1000px;z-index: 10;">
      <div style="height: 800px;position: relative;overflow-x: auto; overflow-y: hidden;">
        <vue-office-excel :src="modelValue" v-if="officeType == 'excel'" style="height: 100%; width: 100vw;  " />
        <vue-office-docx :src="modelValue" v-else-if="officeType == 'word'" style="height: 100%;" />

        <vue-office-pdf :src="modelValue" v-else-if="officeType == 'pdf'" style="height: 100%;" />

        <vue-office-pptx :src="modelValue" v-else-if="officeType == 'ppt'" style="height: 100%;" />
      </div>

    </ElDialog>
  </teleport>
</template>

<style scoped lang="scss"></style>
